package com.zl.tcbnewcar.ui.fragment;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.deahu.activity.MainActivity;
import com.google.gson.Gson;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.zl.tcbnewcar.R;
import com.zl.tcbnewcar.base.BaseFragment;
import com.zl.tcbnewcar.base.RecyclerAdapter;
import com.zl.tcbnewcar.base.UniversalAdapter;
import com.zl.tcbnewcar.base.UniversalViewHolder;
import com.zl.tcbnewcar.base.ViewHolder;
import com.zl.tcbnewcar.model.CarAdvertEntity;
import com.zl.tcbnewcar.model.CarInfoEntity;
import com.zl.tcbnewcar.model.CityBean;
import com.zl.tcbnewcar.ui.activity.CarDetailActivity;
import com.zl.tcbnewcar.ui.activity.CarHangCollectActivity;
import com.zl.tcbnewcar.ui.activity.CarSearchActivity;
import com.zl.tcbnewcar.ui.activity.CarShareListActivity;
import com.zl.tcbnewcar.ui.activity.MessageActivity;
import com.zl.tcbnewcar.ui.activity.SendCarActivity;
import com.zl.tcbnewcar.ui.activity.ServiceListActivity;
import com.zl.tcbnewcar.ui.activity.UsedGoodsListActivity;
import com.zl.tcbnewcar.ui.activity.WebActivity;
import com.zl.tcbnewcar.ui.dialog.AddressDialog;
import com.zl.tcbnewcar.utils.API;
import com.zl.tcbnewcar.utils.BindDataUtils;
import com.zl.tcbnewcar.utils.HttpUtils;
import com.zl.tcbnewcar.utils.LocationUtils;
import com.zl.tcbnewcar.utils.SpUtlis;
import com.zl.tcbnewcar.utils.SystemUtils;
import com.zl.tcbnewcar.view.LocalADImageHolderView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Request;

/**
 * @author zhanglei
 * @date 18/2/22
 */
public class HomeFragment extends BaseFragment {

    @BindView(R.id.tv_city)
    TextView tvCity;
    Unbinder unbinder;
    @BindView(R.id.iv_message)
    ImageView ivMessage;
    @BindView(R.id.fab_loop)
    FloatingActionButton fabLoop;
    @BindView(R.id.et_search_data)
    TextView etSearchData;
    @BindView(R.id.message_iv_tag)
    ImageView messageIvTag;
    @BindView(R.id.home_trl)
    TwinklingRefreshLayout homeTrl;
    @BindView(R.id.home_listView)
    ListView homeListView;

    private RecyclerAdapter<String> gAdapter;
    private UniversalAdapter<CarInfoEntity> mAdapter;
    private List<CarInfoEntity> mList = new ArrayList<>();
    private List<String> gList = new ArrayList<>();
    private List<CarAdvertEntity> ivList = new ArrayList<>();
    private String[] names = {"发布车源", "赚取佣金", "车行关注", "违章查询", "杂货铺", "违章处理", "维修保养", "保险服务", "年审服务", "信贷金融"};
    private Integer[] icons = {R.mipmap.fabu, R.mipmap.zhongjie, R.mipmap.shoucang, R.mipmap.chaxun,
            R.mipmap.zhongjie, R.mipmap.weizhang, R.mipmap.weixiu, R.mipmap.baoxian, R.mipmap.nianshen, R.mipmap.luntan};
    private AddressDialog addressDialog;
    private int page = 1;
    private boolean isToTop = false;
    //是否加载到了数据的尾部（没有更多数据了）
    private boolean isLast = false;
    private ConvenientBanner homeBanner;
    private RecyclerView homeGrid;
    private View viewBottom;
    private TextView tvBottom;
    private JSONObject tabJson;

    public HomeFragment() {
        // Required empty public constructor
    }

    public static HomeFragment newInstance() {

        Bundle args = new Bundle();

        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        initData();
        initListener();
        return view;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            tvCity.setText(SpUtlis.getLocationData(mActivity).getCityName());
        }
    }

    private void initListener() {
        homeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(mActivity, CarDetailActivity.class);
                intent.putExtra("data", mList.get((i - 1)));
                startActivity(intent);
            }
        });

        gAdapter.setOnItemClickListener(new RecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                switch (position) {
                    //发布车源
                    case 0:
                        SystemUtils.toActivity(mActivity, new Intent(mActivity, SendCarActivity.class));
                        break;
                    //赚取佣金
                    case 1:
                        SystemUtils.toActivityForResult(mActivity, new Intent(mActivity, CarShareListActivity.class), 1);
                        break;
                    //车行关注
                    case 2:
                        SystemUtils.toActivityForResult(mActivity, new Intent(mActivity, CarHangCollectActivity.class), 1);
                        break;
                    //违章查询
                    case 3:
                        startActivity(new Intent(mActivity, MainActivity.class));
                        break;
                    //杂货铺
                    case 4:
                        if (tabJson == null || TextUtils.isEmpty(tabJson.toString())) {
                            showToast("数据还未加载完毕");
                            return;
                        }
                        Intent intent = new Intent(mActivity, UsedGoodsListActivity.class);
                        intent.putExtra("tabJson", tabJson.toString());
                        startActivity(intent);
                        break;
                    //违章处理
                    case 5:
                        Intent intent1 = new Intent(mActivity, ServiceListActivity.class);
                        intent1.putExtra("type", 1);
                        startActivity(intent1);
                        break;
                    //维修保养
                    case 6:
                        Intent intent2 = new Intent(mActivity, ServiceListActivity.class);
                        intent2.putExtra("type", 2);
                        startActivity(intent2);
                        break;
                    //保险服务
                    case 7:
                        Intent intent3 = new Intent(mActivity, ServiceListActivity.class);
                        intent3.putExtra("type", 3);
                        startActivity(intent3);
                        break;
                    //年审服务
                    case 8:
                        Intent intent4 = new Intent(mActivity, ServiceListActivity.class);
                        intent4.putExtra("type", 4);
                        startActivity(intent4);
                        break;
                    //信贷金融
                    case 9:
                        Intent intent5 = new Intent(mActivity, ServiceListActivity.class);
                        intent5.putExtra("type", 5);
                        startActivity(intent5);
                        break;
                }
            }
        });

        addressDialog.setOnAddressDataListener(new AddressDialog.OnAddressDataListener() {
            @Override
            public void addressData(CityBean cityBean) {
                tvCity.setText(cityBean.getCityName());
                page = 1;
                getListData();
            }
        });

        homeTrl.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                page = 1;
                getListData();
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                //没有更多数据了，直接返回
                if (isLast) {
                    homeTrl.finishLoadmore();
                    return;
                }
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page++;
                        getListData();
                    }
                }, 800);
            }
        });

        homeBanner.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                CarAdvertEntity carAdvertEntity = ivList.get(position);
                if (TextUtils.isEmpty(carAdvertEntity.getAdvertHtml())) return;
                Intent intent = new Intent(mActivity, WebActivity.class);
                intent.putExtra("url", carAdvertEntity.getAdvertHtml());
                intent.putExtra("title", carAdvertEntity.getAdvertName());
                intent.putExtra("name", "ADActivity");
                intent.putExtra("isFinish", true);
                startActivity(intent);
            }
        });
    }

    private void initData() {
        for (int i = 0; i < names.length; i++) {
            gList.add(names[i]);
        }
        gAdapter.notifyDataSetChanged();
        CityBean locationData = SpUtlis.getLocationData(mActivity);
        tvCity.setText(locationData.getCityName());
        //获取最新发布的车辆
        getListData();
        //获取首页广告
        getMainAdvert();
        //获取杂货铺标签名称
        getTagList();
    }


    /**
     * 获取轮播广告
     */
    private void getMainAdvert() {
        HttpUtils.getInstance().GET(mActivity, API.getMainAdvert, new HttpUtils.OnOkHttpCallback() {
            @Override
            public void onSuccess(String body) {
                try {
                    JSONObject object = new JSONObject(body);
                    if (object.optBoolean("result")) {
                        ivList.clear();
                        JSONArray array = object.optJSONArray("data");
                        for (int i = 0; i < array.length(); i++) {
                            ivList.add(new Gson().fromJson(array.optString(i), CarAdvertEntity.class));
                        }
                        //自定义你的Holder，实现更多复杂的界面，不一定是图片翻页，其他任何控件翻页亦可。
                        homeBanner.setPages(
                                new CBViewHolderCreator<LocalADImageHolderView>() {
                                    @Override
                                    public LocalADImageHolderView createHolder() {
                                        return new LocalADImageHolderView();
                                    }
                                }, ivList);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Request error, Exception e) {

            }
        });
    }

    /**
     * 获取杂货铺标签数据
     */
    private void getTagList() {
        HttpUtils.getInstance().GET(mActivity, API.getGroceriesCache, new HttpUtils.OnOkHttpCallback() {
            @Override
            public void onSuccess(String body) {
                try {
                    tabJson = new JSONObject(body);
                    if (!tabJson.optBoolean("result")) {
                        return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.e("body", body);
            }

            @Override
            public void onError(Request error, Exception e) {
                Log.e("body", "");
            }
        });
    }

    private void getListData() {
        String cityCode = SpUtlis.getLocationData(mActivity).getCityCode();
        Map<String, String> params = new HashMap<>();
        params.put("did", "");
        params.put("cityCode", cityCode);
        params.put("page", page + "");

        HttpUtils.getInstance().Post(mActivity, params, API.getCarList, new HttpUtils.OnOkHttpCallback() {
            @Override
            public void onSuccess(String body) {
                try {
                    stopLoop(fabLoop);
                    if (page == 1) {
                        //加载首页数据，将isLast设置为false
                        isLast = false;
                        mList.clear();
                        homeTrl.finishRefreshing();
                    } else {
                        homeTrl.finishLoadmore();
                    }

                    JSONObject object = new JSONObject(body);
                    JSONArray array = object.optJSONArray("items");
                    for (int i = 0; i < array.length(); i++) {
                        mList.add(new Gson().fromJson(array.optString(i), CarInfoEntity.class));
                    }
                    mAdapter.notifyDataSetChanged();

                    //是否显示底部布局
                    if (array.length() <= 0) {
                        //没有更多数据了将isLast设置为false
                        isLast = true;
                        if (homeListView.getFooterViewsCount() <= 0) {
                            tvBottom.setText("共" + mList.size() + "条车辆信息");
                            homeListView.addFooterView(viewBottom);
                        } else {
                            homeListView.removeFooterView(viewBottom);
                        }
                    } else {
                        if (homeListView.getFooterViewsCount() > 0) {
                            homeListView.removeFooterView(viewBottom);
                        }
                    }

                    //是否回到顶部
                    if (isToTop) {
                        isToTop = false;
                        homeListView.setSelection(0);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Request error, Exception e) {
                if (page == 1) {
                    mList.clear();
                    homeTrl.finishRefreshing();
                } else {
                    homeTrl.finishLoadmore();
                }
            }
        });
    }

    private void initView() {
        gAdapter = new RecyclerAdapter<String>(mActivity, gList, R.layout.home_grid_item) {

            @Override
            protected void convert(ViewHolder holder, String s, int position) {
                holder.setText(R.id.tv_name, s);
                holder.setImageResource(R.id.image_icon, icons[position]);
            }
        };
        mAdapter = new UniversalAdapter<CarInfoEntity>(mActivity, mList, R.layout.home_list_item) {
            @Override
            public void convert(UniversalViewHolder holder, int position, CarInfoEntity carInfoEntity) {
                BindDataUtils.bindCarData(mActivity, holder, carInfoEntity);
            }
        };
        homeListView.setAdapter(mAdapter);

        //ListView的头部布局
        View hearder = LayoutInflater.from(mActivity).inflate(R.layout.home_heard_layout, null);
        homeBanner = hearder.findViewById(R.id.home_banner);
        homeGrid = hearder.findViewById(R.id.home_grid);
        homeGrid.setNestedScrollingEnabled(false);
        homeGrid.setLayoutManager(new StaggeredGridLayoutManager(5, StaggeredGridLayoutManager.VERTICAL));
        homeGrid.setAdapter(gAdapter);
        initBanner(homeBanner);
        initProgress(homeTrl);

        //ListView尾部布局
        viewBottom = LayoutInflater.from(mActivity).inflate(R.layout.tv_bottom_layout, null);
        tvBottom = viewBottom.findViewById(R.id.tv_bottom);

        //为listView添加头部
        homeListView.addHeaderView(hearder);
        //初始化城市选择器
        addressDialog = new AddressDialog(mActivity);

    }

    @Override
    public void onResume() {
        super.onResume();
        getNoReadMessage(messageIvTag);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.tv_city, R.id.iv_message, R.id.et_search_data, R.id.fab_loop})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //选择城市
            case R.id.tv_city:
                addressDialog.showDialog(view);
                break;
            //进入消息中心
            case R.id.iv_message:
                SystemUtils.toActivity(mActivity, new Intent(mActivity, MessageActivity.class));
                break;
            //进入搜索中心
            case R.id.et_search_data:
                mActivity.startActivityForResult(new Intent(mActivity, CarSearchActivity.class), CarSearchActivity.SEARCHDATA);
                break;
            case R.id.fab_loop:
                updateData();
                break;
        }
    }

    /**
     * 刷新数据
     */
    private void updateData() {
        isToTop = true;
        startLoop(fabLoop);
        page = 1;
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getListData();
            }
        }, 400);
    }

    public class LocalImageHolderView implements Holder<Integer> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, final int position, Integer data) {
            imageView.setImageResource(data);
        }
    }
}
